import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken, removeToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, 
  timeout: 5000 
})

// 请求统一拦截处理
service.interceptors.request.use(
  config => {
    // 是否需要设置 token
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(

  response => {
    // 下载excel时放行
    if (response.config.responseType === 'blob') {
      return response
    }
    const res = response.data
    const code = response.data.code
    // 如果响应有新的token，则更新
    // if (res.token) {
    //   store.commit('user/SET_TOKEN', res.token)
    //   return response
    // }

    // token过期
    if (code === 401) {
      return new Promise((resolve, reject) => {
        MessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          showCancelButton: false,
          type: 'warning'
        }).then(() => {
          removeToken()
          console.log('重新登录')
          router.push('/login')
          reject(new Error('登录已过期')) // 显式拒绝
        }).catch(() => {
          reject(new Error('登录已过期')) // 防止用户意外关闭弹窗
        })
      })
    }

    else if (code === 500) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) 
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
